package com.yunkeji.framework.interceptor;

import cn.hutool.core.util.StrUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author o
 * @description 自定义日志拦截器
 * @date 2024/4/11
 */
public class MDCInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 客户端可以传入链路ID，需要唯一性
        String traceId = request.getHeader(MDCTraceUtil.TRACE_ID_HEADER);
        if (!StrUtil.isEmpty(traceId)) {
            MDCTraceUtil.putTrace(request.getHeader(MDCTraceUtil.TRACE_ID_HEADER));
        } else {
            MDCTraceUtil.addTrace();
        }
        return true;
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        MDCTraceUtil.removeTrace();
    }
}
